package com.servlet.teacher;

import com.bean.BookBean;
import com.dao.BooksDao;
import com.dao.impl.BooksDaoImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JsonUtil;
import com.util.ProxyUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;


@WebServlet("/UpdateBooksServlet")
public class UpdateBooksServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       String bookid =   req.getParameter("bookid");
           //调用Dao的删除方法
        BooksDao booksDao = (BooksDao)ProxyUtil.getDaoProxy(new BooksDaoImpl());

        JsonUtil jsonUtil = new JsonUtil();
        try {
          /*  String book_id =  req.getParameter("book_id");//分别取出前端传递过来的数据
            String book_name =  req.getParameter("book_name");
            String isbn =  req.getParameter("isbn");
            String author =  req.getParameter("author");
            String publish =  req.getParameter("publish");
            String publish_date =  req.getParameter("publish_date");
            String pages =  req.getParameter("pages");
            bookBean.setBook_id(Integer.parseInt(book_id));*/
            BookBean bookBean = new BookBean();


                //将客户端传递过来的请求参数封装到bookBean对象中
                //要求：参数名必需与bookBean中的属性名有对应关系
                System.out.println("反射前的BookBean对象中的属性值为:"+bookBean);
                BeanUtils.populate(bookBean,req.getParameterMap());
                System.out.println("反射后的BookBean对象中的属性值为:"+bookBean);

                int res =  booksDao.update(bookBean);

                jsonUtil.setCode(0);
                jsonUtil.setMsg("成功");






        } catch (SQLException e) {
            e.printStackTrace();
            jsonUtil.setCode(1);
            jsonUtil.setMsg("系统错误:"+e.getMessage());
        } catch (Exception e){
            e.printStackTrace();
            jsonUtil.setCode(1);
            jsonUtil.setMsg("系统错误:"+e.getMessage());
        }

        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson =  gsonBuilder.create();

        String jsonStr =  gson.toJson(jsonUtil);


        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.print(jsonStr);
    }


}
